/**
 * Created by macos on 14/11/11.
 */
var  crypto = require('crypto');

module.exports = {

  types:{
    description:function(value) {
      return true;
    }
  },

  attributes: {
    serviceName: {
      type: 'string',
      required: true,
      description: '消息服务的名称'
    },
    userId: {
      type: 'string',
      required: true,
      description: '授权用户的id'
    },
    username: {
      type: 'string',
      required: true,
      description: '授权用户的用户名'
    },
    responseType: {
      type: 'string',
      required: true,
      enum: ['code','token'],
      description: '返回类型'
    },
    redirectUri: {
      type: 'string',
      required: true,
      description: '授权后重定向的回调链接地址'
    },
    scope: {
      type: 'string',
      required: false,
      description: '应用授权作用域'
    },
    code: {
      type: 'string',
      required: true,
      description: '授权码'
    },
      expiresTime: {
      type: 'string',
      required: true
    },
    checkTTL: function() {
      var obj = this.toObject();
      return (obj.expiresTime > new Date().getTime());
    }
  },

  beforeValidate:function(values,next) {
      values.code = crypto.randomBytes(32).toString('hex');
      values.expiresTime = new Date().getTime() + 300 * 1000+"";
      next();
  },

  beforeCreate: function (values, next) {
      MessageService.findOne({name:values.serviceName})
          .exec(function(err, result){
              if (err) {
                  sails.log.error(err);
                  return next(err);
              }

              if (_.has(result, 'id')) {
                  if(values.redirectUri){
                      if(values.redirectUri == result.redirectUri){
                          return next();
                      }else{
                          err = new Error();
                          err.message = 'Wrong RedirectUri provided!';
                          err.status = 403;
                          return next(err);
                      }
                  }else{
                      err = new Error();
                      err.message = 'Wrong RedirectUri provided!';
                      err.status = 404;
                      return next(err);
                  }
              } else {

                  err = new Error();
                  err.message = '\''+ values.serviceName + '\' is not exist!';
                  err.status = 404;

                  return next(err);
              }

          });
  },

  beforeUpdate:function (values, next) {

  }
}